import React, { useState, useRef, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import '../styles/player.css'
import apiService from '../utils/api.js'
import AddToPlaylistModal from './AddToPlaylistModal.jsx'

/**
 * 音乐播放器组件
 * @component
 * @param {Object} props - 组件属性
 * @param {Object} props.song - 当前播放的歌曲对象
 * @param {boolean} props.isPlaying - 是否正在播放
 * @param {Array} props.playlist - 播放列表
 * @param {number} props.currentIndex - 当前播放歌曲在播放列表中的索引
 * @param {Function} props.playSong - 播放指定歌曲的回调函数
 * @param {Function} props.togglePlay - 切换播放/暂停状态的回调函数
 * @param {Function} props.playNextSong - 播放下一首歌曲的回调函数
 * @param {Function} props.playPreviousSong - 播放上一首歌曲的回调函数
 * @param {boolean} props.isUserLoggedIn - 用户是否已登录
 * @returns {JSX.Element} 音乐播放器组件
 */
function Player({ song, isPlaying, togglePlay, playlist, currentIndex, playPreviousSong, playNextSong, isUserLoggedIn }) {
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(300) // 模拟5分钟的歌曲
  const [volume, setVolume] = useState(80) // 默认音量80%
  const [isFavorite, setIsFavorite] = useState(false)
  const [isLiked, setIsLiked] = useState(false) // 点赞状态
  const [isPlaylistVisible, setIsPlaylistVisible] = useState(false) // 播放列表显示状态
  const [isAddToPlaylistModalVisible, setIsAddToPlaylistModalVisible] = useState(false) // 添加到播放列表模态框状态
  const [isHovered, setIsHovered] = useState(false) // 鼠标是否悬停在播放器上
  const audioRef = useRef(null)
  const playerRef = useRef(null)
  const location = useLocation() // 获取当前路由位置
  const navigate = useNavigate()

  // 处理鼠标悬停事件
  const handleMouseEnter = () => {
    setIsHovered(true)
  }

  const handleMouseLeave = () => {
    setIsHovered(false)
  }

  // 切换播放列表显示状态
  const togglePlaylistVisibility = () => {
    setIsPlaylistVisible(!isPlaylistVisible)
  }

  // 显示添加到播放列表模态框
  const showAddToPlaylistModal = () => {
    if (!song || !isUserLoggedIn) {
      alert('请先登录后再添加到歌单')
      return
    }
    setIsAddToPlaylistModalVisible(true)
  }

  // 关闭添加到播放列表模态框
  const closeAddToPlaylistModal = () => {
    setIsAddToPlaylistModalVisible(false)
  }

  // 添加到播放列表成功回调
  const handleAddToPlaylistSuccess = () => {
    console.log('歌曲成功添加到播放列表')
  }

  // 在播放列表中点击播放指定歌曲
  const handlePlaylistSongClick = (song, index) => {
    if (song && song.id) {
      playSong(song, index)
    }
  }

  // 格式化时间为分:秒格式
  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`
  }

  // 处理进度条变化
  const handleProgressChange = (e) => {
    const newTime = e.target.value
    setCurrentTime(newTime)
    if (audioRef.current) {
      audioRef.current.currentTime = newTime
    }
  }

  // 模拟播放进度更新
  useEffect(() => {
    let interval
    if (isPlaying) {
      interval = setInterval(() => {
        setCurrentTime(prev => {
          if (prev >= duration) {
            // 如果有播放列表，播放下一首
            if (playlist && playlist.length > 0) {
              playNextSong()
            } else {
              togglePlay()
            }
            return 0
          }
          return prev + 0.5
        })
      }, 500)
    }
    return () => clearInterval(interval)
  }, [isPlaying, duration, togglePlay, playlist, playNextSong])

  // 更新音频元素的音量
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume / 100
    }
  }, [volume])

  // 当isPlaying状态变化时，直接控制音频元素的播放/暂停
  useEffect(() => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.play().catch(err => {
          console.error('播放失败:', err)
          // 如果播放失败，通过togglePlay重置isPlaying状态
          togglePlay()
        })
      } else {
        audioRef.current.pause()
      }
    }
  }, [isPlaying, song?.audioUrl])

  // 处理音量变化

  // 路由变化时不需要收缩播放器，只由鼠标悬停控制
  const handleVolumeChange = (e) => {
    const newVolume = parseInt(e.target.value)
    setVolume(newVolume)
  }

  // 切换静音
  const toggleMute = () => {
    if (volume > 0) {
      setVolume(0)
    } else {
      setVolume(80) // 恢复到默认音量
    }
  }

  // 处理收藏/取消收藏
  const handleToggleFavorite = () => {
    if (!song || !song.id) return
    
    if (!isUserLoggedIn) {
      console.log('请先登录后再收藏歌曲')
      // 实际项目中可以显示登录提示弹窗
      return
    }

    const newIsFavorite = !isFavorite
    setIsFavorite(newIsFavorite)

    // 调用API - 统一使用post请求，后端会处理具体的收藏/取消收藏逻辑
    apiService.toggleFavorite(song.id, newIsFavorite)
      .then(() => console.log(newIsFavorite ? '收藏成功' : '取消收藏成功'))
      .catch(err => {
        console.error(newIsFavorite ? '收藏失败' : '取消收藏失败:', err)
        // 失败时回滚状态
        setIsFavorite(isFavorite)
      })
  }

  // 处理点赞/取消点赞
  const handleToggleLike = () => {
    if (!song || !song.id) return
    
    if (!isUserLoggedIn) {
      console.log('请先登录后再点赞歌曲')
      // 实际项目中可以显示登录提示弹窗
      return
    }

    const newIsLiked = !isLiked
    setIsLiked(newIsLiked)

    // 调用API - 统一使用post请求，后端会处理具体的点赞/取消点赞逻辑
    apiService.toggleLike(song.id, newIsLiked)
      .then(() => console.log(newIsLiked ? '点赞成功' : '取消点赞成功'))
      .catch(err => {
        console.error(newIsLiked ? '点赞失败' : '取消点赞失败:', err)
        // 失败时回滚状态
        setIsLiked(isLiked)
      })
  }

  // 当切换歌曲时，获取并设置真实的收藏和点赞状态
  useEffect(() => {
    if (song && song.id) {
      // 默认重置为未收藏和未点赞状态
      setIsFavorite(false)
      setIsLiked(false)
      
      // 如果用户已登录，调用API获取真实状态
      if (isUserLoggedIn) {
        apiService.getSongStatus(song.id)
          .then(status => {
            if (status) {
              console.log(status)
              setIsFavorite(status.isCollected || false)
              setIsLiked(status.isLiked || false)
            }
          })
          .catch(err => {
            console.error('获取歌曲状态失败:', err)
          })
      }
    }
  }, [song?.id, isUserLoggedIn])
  
  // 路由变化时不再控制播放器的显示状态，只由鼠标悬停控制

  // 计算最终的播放器样式 - 只由鼠标悬停控制显示
  const shouldShowFullPlayer = isHovered
  
  return (
    <div 
      ref={playerRef}
      className="player-container player-expanded"
      style={{ 
        bottom: shouldShowFullPlayer ? '0' : '-110px' 
      }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {/* 隐藏的音频元素 */}
      <audio 
        ref={audioRef} 
        src={song?.audioUrl} 
        onTimeUpdate={(e) => setCurrentTime(e.target.currentTime)}
        onLoadedMetadata={(e) => setDuration(e.target.duration)}
        onEnded={() => {
          // 如果有播放列表，播放下一首
          if (playlist && playlist.length > 0) {
            playNextSong()
          } else {
            // 否则停止播放
        togglePlay()
          }
        }}
        onError={(e) => {
          console.error('音频播放错误:', e)
          togglePlay()
        }}
      />
      
      {/* 歌曲信息 */}
      <div className="song-info">
        <img src={song.coverImageUrl} alt={song.title} className="song-cover" />
        <div className="song-details">
          <h3 className="song-title">{song.title}</h3>
          <p className="song-artist">{song.artist?.name}</p>
        </div>
        <div className="song-actions">
            <button 
              className={`btn-like ${!isUserLoggedIn ? 'btn-disabled' : ''}`} 
              onClick={handleToggleFavorite}
              disabled={!isUserLoggedIn}
              title={isUserLoggedIn ? (isFavorite ? '取消收藏' : '收藏') : '请先登录'}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill={isFavorite ? "#ff4757" : "none"} xmlns="http://www.w3.org/2000/svg">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" stroke={isFavorite ? "#ff4757" : "#666"} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
            <button 
              className={`btn-dislike ${!isUserLoggedIn ? 'btn-disabled' : ''}`} 
              onClick={handleToggleLike}
              disabled={!isUserLoggedIn}
              title={isUserLoggedIn ? (isLiked ? '取消点赞' : '点赞') : '请先登录'}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill={isLiked ? "#3742fa" : "none"} xmlns="http://www.w3.org/2000/svg">
                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" stroke={isLiked ? "#3742fa" : "#666"} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
          </div>
      </div>
      
      {/* 播放控制 */}
      <div className="playback-controls">
        <button className="btn-skip-back" onClick={playPreviousSong}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 20V4L12 12M5 20V4L12 12" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <button className="btn-play-pause" onClick={togglePlay}>
          {isPlaying ? (
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="6" y="4" width="4" height="16" rx="1" fill="#fff"/>
              <rect x="14" y="4" width="4" height="16" rx="1" fill="#fff"/>
            </svg>
          ) : (
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M8 5V19L19 12L8 5Z" fill="#fff"/>
            </svg>
          )}
        </button>
        <button className="btn-skip-forward" onClick={playNextSong}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 20V4L5 12M19 20V4L12 12" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
      
      {/* 进度条 */}
      <div className="progress-container">
        <span className="time-current">{formatTime(currentTime)}</span>
        <input
          type="range"
          min="0"
          max={duration}
          value={currentTime}
          onChange={handleProgressChange}
          className="progress-bar"
        />
        <span className="time-total">{formatTime(duration)}</span>
      </div>
      
      {/* 播放器现在只由鼠标悬停控制显示/隐藏，无需展开/收缩按钮 */}
      
      {/* 音量控制 */}
      <div className="volume-controls">
        <button className="btn-volume" onClick={toggleMute}>
          {volume === 0 ? (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M16 8L14 6M16 16L14 18M19 12H17M3 9v6h4l5 5V4L7 9H3z" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          ) : (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M14.12 10.18L17 7.3a1 1 0 0 1 1.66.66V16.03a1 1 0 0 1-1.66.66l-2.88-2.88a1 1 0 0 1 0-1.44z" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M3 9v6h4l5 5V4L7 9H3z" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </button>
        <input 
          type="range" 
          min="0" 
          max="100" 
          value={volume} 
          onChange={handleVolumeChange} 
          className="volume-bar" 
        />
      </div>

      {/* 添加到歌单模态框 */}
      <AddToPlaylistModal
        visible={isAddToPlaylistModalVisible}
        onClose={closeAddToPlaylistModal}
        onAddSuccess={handleAddToPlaylistSuccess}
        selectedSong={song}
      />
    </div>
  )
}

export default Player